/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.angis.xiugallery.image.ui;

import java.io.IOException;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import cc.angis.xiugallery.R;
import cc.angis.xiugallery.common.GlobalConst;
import cc.angis.xiugallery.data.ImageData;
import cc.angis.xiugallery.db.ImageDescDBHelper;
import cc.angis.xiugallery.db.TableConstants;
import cc.angis.xiugallery.image.util.ImageCache;
import cc.angis.xiugallery.image.util.ImageWorker;

import com.actionbarsherlock.app.SherlockFragment;

/**
 * This fragment will populate the children of the ViewPager from {@link ImageDetailActivity}.
 */
public class ImageDetailFragment extends SherlockFragment{
    private String mImageId;
    private ImageView mImageView;
    private ImageWorker mImageWorker;
    
    private TextView mDescTextView;
    
    private Button mVoicePlayButton;
    
    private MediaPlayer mMediaPlayer;
    
    private String mVoicePath;

    
    /**
     * Factory method to generate a new instance of the fragment given an image number.
     *
     * @param imageNum The image number within the parent adapter to load
     * @return A new instance of ImageDetailFragment with imageNum extras
     */
    public static ImageDetailFragment newInstance(String imageId) {
        final ImageDetailFragment f = new ImageDetailFragment();

        final Bundle args = new Bundle();
        args.putString(GlobalConst.INTENT_IMAGE_ID, imageId);
        f.setArguments(args);
        return f;
    }

    /**
     * Empty constructor as per the Fragment documentation
     */
    public ImageDetailFragment() {}

    /**
     * Populate image number from extra, use the convenience factory method
     * {@link ImageDetailFragment#newInstance(int)} to create this fragment.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mImageId = getArguments() != null ? getArguments().getString(GlobalConst.INTENT_IMAGE_ID) : "-1";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate and locate the main ImageView
        final View v = inflater.inflate(R.layout.image_detail_fragment, container, false);
        v.setTag(mImageId);
        mImageView = (ImageView) v.findViewById(R.id.imageView);
        mDescTextView = (TextView) v.findViewById(R.id.desc_text);
        mVoicePlayButton = (Button) v.findViewById(R.id.voiceplaybutton);
        mVoicePlayButton.setOnClickListener(new PlayOnClickListener());
		mVoicePlayButton.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
				builder.setTitle(R.string.delete_voice_title)
				.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						ImageDescDBHelper dbHelper = new ImageDescDBHelper(getActivity(), TableConstants.TABLE_IMAGE_DESC);
						try{
							dbHelper.deleteByImgIdAndType(Long.parseLong(mImageId), 0);
							mVoicePlayButton.setVisibility(View.GONE);
						} catch(Exception e){
							e.printStackTrace();
						} finally{
							dbHelper.closeDB();
						}
					}

				}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}

				}).show();
				return false;
			}
		});
        new LoadViewTask().execute(Long.parseLong(mImageId));
        return v;
    }

    public String getImageId() {
		return mImageId;
	}

	public void setImageId(String mImageId) {
		this.mImageId = mImageId;
	}

	@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Use the parent activity to load the image asynchronously into the ImageView (so a single
        // cache can be used over all pages in the ViewPager
        if (ImageDetailActivity.class.isInstance(getActivity())) {
            mImageWorker = ((ImageDetailActivity) getActivity()).getImageWorker();
            mImageWorker.loadImage(mImageId, mImageView);
        }

        // Pass clicks on the ImageView to the parent activity to handle
        if (OnClickListener.class.isInstance(getActivity())) {
            mImageView.setOnClickListener((OnClickListener) getActivity());
        }
    }

    /**
     * Cancels the asynchronous work taking place on the ImageView, called by the adapter backing
     * the ViewPager when the child is destroyed.
     */
    public void cancelWork() {
        ImageWorker.cancelWork(mImageView);
        mImageView.setImageDrawable(null);
        mImageView = null;
    }
    
    @Override
    public void onDestroyView(){
    	final ImageCache cache = mImageWorker.getImageCache();
        if (cache != null) {
            mImageWorker.getImageCache().clearCaches();
//            DiskLruCache.clearCache(getActivity(), ImageFetcher.HTTP_CACHE_DIR);
//            Toast.makeText(getActivity(), R.string.clear_cache_complete,
//                    Toast.LENGTH_SHORT).show();
        }
		super.onDestroyView();
    }
    
    private class LoadViewTask extends AsyncTask<Long, Void, List<ImageData>>{

		@Override
		protected List<ImageData> doInBackground(Long... params) {
			ImageDescDBHelper dbHelper = new ImageDescDBHelper(getActivity(), TableConstants.TABLE_IMAGE_DESC);
			try{
				return dbHelper.getAllByImgId(params[0]);
			} catch(Exception e){
				e.printStackTrace();
			} finally{
				dbHelper.closeDB();
			}
			return null;
		}

		@Override
		protected void onPostExecute(List<ImageData> result) {
			if (result == null || result.size() <=0){
				mDescTextView.setVisibility(View.VISIBLE);
				mDescTextView.setText(R.string.img_no_content);
				return;
			}
			for (final ImageData data:result){
				if (data.getType() == 1){
					mDescTextView.setVisibility(View.VISIBLE);
					mDescTextView.setText(data.getDescText());
				} 
				if (data.getType() == 0){
					mVoicePlayButton.setVisibility(View.VISIBLE);
					mVoicePlayButton.setContentDescription(data.getVoicePath());
					mVoicePath = data.getVoicePath();
				}
			}
			super.onPostExecute(result);
		}
    }
    
    private class PlayOnClickListener implements OnClickListener {
    	@Override
		public void onClick(View v) {
			mMediaPlayer = new MediaPlayer();
			try {
				mMediaPlayer.setDataSource(mVoicePlayButton.getContentDescription().toString());
				mMediaPlayer.prepare();
				mMediaPlayer.start();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			mVoicePlayButton.setOnClickListener(new PauseOnClickListener());
			mVoicePlayButton.setText(R.string.media_pause);
			mMediaPlayer.setOnCompletionListener(new OnCompletionListener(){
                 @Override
                 public void onCompletion(MediaPlayer mp) {
                     mp.release();
                     mVoicePlayButton.setOnClickListener(new PlayOnClickListener());
                     mVoicePlayButton.setText(R.string.play_audio);
                 }
              });
		}
    }
    
    private class PauseOnClickListener implements OnClickListener {
    	@Override
		public void onClick(View v) {
			try {
				mMediaPlayer.pause();
				length = mMediaPlayer.getCurrentPosition();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} 
			mVoicePlayButton.setOnClickListener(new ResumeOnClickListener());
			mVoicePlayButton.setText(R.string.media_resume);
		}
    }
    private int length = 0;
    
    private class ResumeOnClickListener implements OnClickListener{
    	@Override
		public void onClick(View v) {
			try {
				mMediaPlayer.seekTo(length);
				mMediaPlayer.start();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} 
			mVoicePlayButton.setOnClickListener(new PauseOnClickListener());
			mVoicePlayButton.setText(R.string.media_pause);
		}
    }

	@Override
	public void onDetach() {
		if(mMediaPlayer != null){
			mMediaPlayer.release();
         }
		super.onDetach();
	}
	
	public void setVoicePath(String voicePath){
		this.mVoicePath = voicePath;
	}
	
}
